package com.googlecode.lohr.parser.combinators;


import java.util.Collections;
import java.util.List;

import com.googlecode.lohr.parser.combinators.node.AbstractNode;

/**
 * 
 * @author Administrator
 *
 * @param <N> the matched node types
 */
public class MatchResults
{
	public final MatchError error;
	
	public final List<AbstractNode> matches;
	
	private MatchResults(MatchError error, List<AbstractNode> matches) 
	{
		this.error= error;
		this.matches= matches;
	}
	
	public MatchResults(String errorMsg, int position) 
	{
		this(new MatchError(errorMsg, position), Collections.<AbstractNode>emptyList());
	}
	public MatchResults(MatchError error) 
	{
		this(error, Collections.<AbstractNode>emptyList());
	}
	
	public MatchResults(List<AbstractNode> matches) 
	{
		this(null, matches);
	}
	
	public boolean success() {
		return error == null && matches != null && !matches.isEmpty();
	}

	public int longestLength() {
		if (matches == null)
			return 0;
		
		int l, m= 0;
		for (AbstractNode node:matches) {
			if (m < (l= node.length()))
				m= l;
		}
		return m;
	}
	
	public String toString() {
		if (!success()) 
			return "Failed at position "+error.position+":"+error.errorMsg;
		String s= "Success, matched "+matches.get(0).getText();
		for (int i= 1; i < matches.size(); i++)
			s+= "\nand "+matches.get(i).getText();
		return s;
	}
}
